package com.demo.wrapper.utils;

import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.Operator;
import co.elastic.clients.elasticsearch._types.query_dsl.TermsQueryField;
import com.demo.wrapper.enums.OperatorEnum;
import com.demo.wrapper.enums.OrderEnum;

import java.util.*;

/**
 * @author arthur_zhou
 */
public class FieldValueUtil {
    /**
     * Object转FieldValue
     *
     * @param val
     * @return
     */
    public static FieldValue fieldValue(Object val) {
        if (Objects.isNull(val)) {
            return null;
        }
        if (val instanceof Integer) {
            return FieldValue.of((int) val);
        }
        if (val instanceof Long) {
            return FieldValue.of((long) val);
        }
        if (val instanceof String) {
            return FieldValue.of((String) val);
        }
        if (val instanceof Boolean) {
            return FieldValue.of((boolean) val);
        }
        if (val instanceof Float) {
            return FieldValue.of((float) val);
        }
        if (val instanceof Double) {
            return FieldValue.of((double) val);
        }
        return null;
    }

    /**
     * Object转TermsQueryField
     *
     * @param val
     * @return
     */
    public static TermsQueryField termsQueryField(Object val) {
        if (!(val instanceof Collection)) {
            return null;
        }
        List<FieldValue> termsFieldList = new ArrayList<>();
        Collection<?> valueList = (Collection<?>) val;
        for (Object o : valueList) {
            Optional.ofNullable(fieldValue(o)).ifPresent(termsFieldList::add);
        }
        return TermsQueryField.of(v -> v.value(termsFieldList));
    }

    /**
     * 获取关系
     *
     * @param operatorEnum
     * @return
     */
    public static Operator operator(OperatorEnum operatorEnum) {
        if (Objects.isNull(operatorEnum)) {
            return null;
        }
        switch (operatorEnum) {
            case OR:
                return Operator.Or;
            case AND:
                return Operator.And;
            default:
                return null;
        }
    }

    /**
     * 排序
     *
     * @param asc
     * @return
     */
    public static SortOrder sortOrder(boolean asc) {
        return asc ? SortOrder.Asc : SortOrder.Desc;
    }

    /**
     * 排序
     *
     * @param orderEnum
     * @return
     */
    public static SortOrder sortOrder(OrderEnum orderEnum) {
        if (Objects.isNull(orderEnum)) {
            return SortOrder.Asc;
        }
        return orderEnum == OrderEnum.ASC ? SortOrder.Asc : SortOrder.Desc;
    }
}
